import PAM30
import time
import sys
import os
import win32gui
import win32con
import win32api

TARGET_URL = "http://www.erepublik.com/en" 
WELLNESS = "wellnessBar"
DAILYCONSUMTION= "DailyConsumtion"
DAILYCONSUMTIONTRIGGER = "DailyConsumtionTrigger"
MONEYVALUE = "side_bar_natural_account_value"
TIME_OUT_VALUE = 300

def expired():
    print "\n\tNework connection Timeout! Please retry\n"
    os._exit(2)

def short_wait(ie, timeout=TIME_OUT_VALUE):
    elapsed = 0
    while (ie._ie.Busy):
        time.sleep(5)
        elapsed += 5
        
    

def get_element_by_classname(ie, tag, name):
    l = ie.getElementsList(tag)
    for e in l:
        if e.classname==name:
            return e
    else:
        return None

def wait_element_by_classname(ie, tag, name, timeout=TIME_OUT_VALUE):
    elapsed = 0
    r = None
    while (not r) and (elapsed < timeout):
        time.sleep(1)
        elapsed += 1
        l = ie.getElementsList(tag)
        for e in l:
            if e.classname==name:
                r = e
                break
    if elapsed >= timeout:expired()
    return r

def get_td_by_classname(ie, name):
    l = ie.getElementsList("TD")
    for e in l:
        if e.classname==name:
            return e
    else:
        return None
    

def get_link_by_text(ie, text):
    l = ie.getElementsList("a")
    for e in l:
        if e.innerText==text:
            return e
    else:
        return None

def get_link_by_id(ie, id):
    l = ie.getElementsList("a")
    for e in l:
        if e.id==id:
            return e
    else:
        return None

def get_div_by_text(ie, text):
    #!FIXME! "top"
    l = ie.getElementsList("div")
    for e in l:
        if e.classname=="top":
            if text==e.innerText.strip().rstrip():
                return e
            #print e.innerText
    else:
        return None

def get_li_by_text(ie, text):
    l = ie.getElementsList("li")
    for e in l:
        if text==e.innerText.strip().rstrip():
            return e
    else:
        return None

def get_li_by_id(ie, id):
    l = ie.getElementsList("li")
    for e in l:
        if e.id==id:
            return e
    else:
        return None

def get_image_by_alt(ie, alt):
    l = ie.getElementsList("IMG")
    for e in l:
        if e.alt==alt:
            return e
    else:
        return None

def get_input_element_by_id(ie, id):
    l = ie.getElementsList("INPUT")
    for e in l:
        if e.id==id:
            return e
    else:
        return None
        
def wait_input_element_by_id(ie, id, timeout=TIME_OUT_VALUE):
    r = None
    elapsed = 0
    while (not r) and (elapsed < timeout):
        time.sleep(1)
        elapsed += 1
        l = ie.getElementsList("INPUT")
        for e in l:
            if e.id==id:
                r = e
                break
    if elapsed >= timeout:expired()
    return r
        


def wait_div_by_text(ie, text, timeout=TIME_OUT_VALUE):
    div = None
    elapsed = 0
    while (not div) and (elapsed < timeout):
        time.sleep(1)
        elapsed += 1
        div = get_div_by_text(ie, text)
    if elapsed >= timeout:expired()
    return div

def wait_link_by_id(ie, id, timeout=TIME_OUT_VALUE):
    link = None
    elapsed = 0
    while (not link) and (elapsed < timeout):
        time.sleep(1)
        elapsed += 1
        link = get_link_by_id(ie, id)
    if elapsed >= timeout:expired()
    return link

def wait_li_by_id(ie, id, timeout=TIME_OUT_VALUE):
    r = None
    elapsed = 0
    while (not r) and (elapsed < timeout):
        time.sleep(1)
        elapsed += 1 
        l = ie.getElementsList("li")
        for e in l:
            if e.id==id:
                r = e
                break
    if elapsed >= timeout:expired()
    return r

def wait_td_by_classname(ie, name, timeout=TIME_OUT_VALUE):
    r = None
    elapsed = 0
    while (not r ) and (elapsed < timeout): 
        time.sleep(1)
        elapsed += 1
        l = ie.getElementsList("TD")
        for e in l:
            if e.classname==name:
                r = e
                break
    if elapsed >= timeout:expired()
    return r

def wait_div_by_id(ie, id, timeout=TIME_OUT_VALUE):
    div = None
    elapsed = 0
    while (not div) and (elapsed < timeout):
        time.sleep(1)
        elapsed += 1
        div = ie.getDiv(id)
    if elapsed >= timeout:expired()
    return div

def check_level(ie):
    div = wait_element_by_classname(ie, "div", "xprank") 
    return float(div.innerText)

def check_gold(ie):
    wait_div_by_id(ie, "side_bar_gold_account_value")
    return float(ie.getDiv("side_bar_gold_account_value").innerText)

def check_money(ie):
    wait_div_by_id(ie, MONEYVALUE)
    return float(ie.getDiv(MONEYVALUE).innerText)

def check_health(ie):
    li_wellnessBar = wait_li_by_id(ie, WELLNESS)
    return float(ie.getElementChildren(li_wellnessBar)[1].innerText)

def get_work_train_reward(ie, text):
    if ie.divExists(text):
    #if wait_div_by_id(ie, text):
        div = ie.getDiv(text)
        ul = ie.getElementChildren(div)   
        work_link = ul[2]
        train_link = ul[4]
        reward_link = ul[6]
        return work_link, train_link, reward_link
    else:
        return None, None, None

def work(ie):
    w,t,r = get_work_train_reward(ie, "daily_tasks")
    
    if w:
        #click work
        ie.clickLink(w)
        time.sleep(3)
        #wait conusmes too much time, usually, we don't need everything loaded to go on //ie._wait()
        div = wait_div_by_text(ie, "Single Espresso 0")
        if div:
            ie.clickElement(div)
            # Start working
            ie.clickLink(wait_link_by_id(ie, "form_submit"))
            sys.stdout.write("\tworking... ")
            time.sleep(3)
            #ie._wait()
            sys.stdout.write("Done\n")
        #fired? find a new job
        else:
            print "\tFired? finding a new job"
            pass #FIXME
            
    else:
        print " Work not available"
    
def train(ie):
    w,t,r = get_work_train_reward(ie, "daily_tasks_full")
    if t:
        ie.clickLink(t)
        time.sleep(3)
        #ie._wait()
        #0 gold 10% improve
        ie.clickElement(wait_div_by_text(ie, "Army boots 0"))
        # Start trainning
        ie.clickLink(wait_link_by_id(ie, "form_submit"))
        time.sleep(3)
        #ie._wait()
        print "Done"
    else:
        print "\ttraining not available"

def reward(ie):
    w,t,r = get_work_train_reward(ie, "daily_tasks_full")
    if r:
        ie.clickLink(r)
        sys.stdout.write("going to reward... ")
        time.sleep(3)
        #ie._wait()
        h = None
        while not h:
            h = get_link_by_text(ie, "Ok")
            time.sleep(3)
            ie._wait()
        #sys.stdout.write("got Ok button ")
        w = win32gui.FindWindow(None, "Erepublik - Windows Internet Explorer")
        win32gui.ShowWindow(w, win32con.SW_MAXIMIZE)
        win32gui.SetForegroundWindow(w)
        win32api.SetCursorPos((635,673))
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0)  
        time.sleep(0.5)  
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0) 
        
        time.sleep(3)
        ie._wait()
        print "Done"
    else:
        print "\tDaily reward not available"

def buy_eat_food(ie):
    while (
        (
            ie.getElementChildren(wait_li_by_id(ie, DAILYCONSUMTION))[1].innerText.strip().rstrip()=='Eat food'
        )
        and (check_health(ie)<99)
    ):
        ie.clickLink(wait_link_by_id(ie, DAILYCONSUMTIONTRIGGER))
        time.sleep(3)
        #ie._wait()
        print "\tEat one food, now health is %d"%check_health(ie)

    if ie.getElementChildren(wait_li_by_id(ie, DAILYCONSUMTION))[1].innerText.strip().rstrip()=='Buy food':
        sys.stdout.write("\tgoing to buy... ")
        #buy
        ie.clickLink(wait_link_by_id(ie, DAILYCONSUMTIONTRIGGER))
        time.sleep(3)
        #ie._wait()
        td = wait_td_by_classname(ie, "m_stock")
        count = float(td.innerText)
        td = wait_td_by_classname(ie, "m_price stprice")
        price = float(td.innerText.split(" ")[0])
        money = check_money(ie)
        health = check_health(ie)
        i = wait_element_by_classname(ie, "INPUT", "shadowed buyField")
        i.value = int(min(count, money/price, (100-health)/2), 10)   #20 slots in bagage, 10 for food
        td = wait_td_by_classname(ie, "m_buy")
        link = ie.getElementChildren(td)[0]
        ie.clickLink(link)
        time.sleep(3)
        #ie._wait()
        #eat
        li_DailyConsumtionTrigger = wait_li_by_id(ie, DAILYCONSUMTION)
        while (
            (
                ie.getElementChildren(wait_li_by_id(ie, DAILYCONSUMTION))[1].innerText.strip().rstrip()=='Eat food'
            )
            and (check_health(ie)<99)
        ):
            ie.clickLink(wait_link_by_id(ie, DAILYCONSUMTIONTRIGGER))
            time.sleep(3)
            #ie._wait()

    


def play_a_user(url, username, password):

    NAME_ID = u'citizen_name'
    PASS_ID = u'citizen_password'
    BUTTON_LOGIN = 'commit'
    
    #open url
    ie = PAM30.PAMIE()
    print "\tIE opened"
    ie.navigate(url) 
    sys.stdout.write("\topening URL... ")
    #ie._wait()
    sys.stdout.write("\tDone\n")
    
    #login
    ie.setTextBox(wait_input_element_by_id(ie, NAME_ID),username)
    ie.setTextBox(wait_input_element_by_id(ie, PASS_ID),password)
    ie.clickButton(BUTTON_LOGIN)
    sys.stdout.write("\tLogging in with username %s... "%username)
    time.sleep(3)
    #ie._wait()
    sys.stdout.write("\tDone\n")
    
    #open userpfofile page
    #img = get_image_by_alt(ie, username)
    #ie.clickImage(img)
    #ie._wait()
    
    #if health below 95, eat read
    print "\tlevel is %d, health is %d, gold is %d, money is %d"%(check_level(ie), check_health(ie), check_gold(ie), check_money(ie))
    if (check_health(ie) >= 92) or (check_money(ie) < 5):
        sys.stdout.write("\tGoing to work... ")
        work(ie)
        sys.stdout.write("\tGoing to train... ")
        train(ie)
        sys.stdout.write("\tGoing to daily reward... ")
        reward(ie) 
        buy_eat_food(ie)
    else:
        buy_eat_food(ie)
        sys.stdout.write("\tGoing to work... ")
        work(ie)
        if (check_health(ie) < 92):
            buy_eat_food(ie)
        sys.stdout.write("\tGoing to train... ")
        train(ie)
        sys.stdout.write("\tGoing to daily reward... ")
        reward(ie)


    #time.sleep(10)
    #logout
    ie.quit()
    print "\tIE closed"


if __name__=='__main__':
    #USERS = [
    #    ('dinnerforfree','onceupon!'),
    #    ('yesmylord', 'onceupon'),
    #    ('saturated', 'onceupon!')
    #]
    USERS = []

    file = open('cfg.txt')
    lines = file.readlines()
    file.close

    for line in lines:
        tmpcontent = line.rstrip().strip()
        if  tmpcontent.startswith('#') or tmpcontent=='':
            pass
        elif tmpcontent.count(',') != 1:
            print "Syntax error in cfg.txt, should be like this 'USERNAME,PASSWORD'"
        else:
            name,password=tmpcontent.split(',')
            name = name.strip().rstrip()
            password = password.strip().rstrip()
            print "found user %s with password %s"%(name, password)
            USERS.append((name,password))

    for u in USERS:
        play_a_user(TARGET_URL, u[0], u[1])




